<template>
  <div class="shopbag">
    <van-nav-bar title="购物车" left-text="返回" left-arrow @click-left="back">
      <template #right>
        <div @click="toggleEdit" v-if="shopbagData.length > 0">
          {{ !edit ? "编辑" : "完成" }}
        </div>
      </template>
    </van-nav-bar>
    <div v-if="shopbagData.length > 0">
      <div class="shopbag-delete">
        <van-list
          v-model="loading"
          :finished="finished"
          finished-text="哎呀, 没有数据啦！"
          offset="100"
          @load="loadingData"
        >
          <van-swipe-cell v-for="(item, index) in shopbagData" :key="item.sid">
            <div class="delete-list">
              <div class="delete-checkd">
                <van-checkbox
                  v-model="item.isChecked"
                  icon-size="20px"
                  @change="select"
                ></van-checkbox>
              </div>
              <div class="delete-img">
                <img class="autoImg" :src="item.small_img" />
              </div>
              <div class="delete-rules">
                <div class="rules-title">{{ item.name }}</div>
                <div class="rules-rule">{{ item.rule }}</div>
              </div>
              <div class="delete-price">
                <div class="price-shop">
                  <span>&yen;{{ item.price }}</span>
                </div>
                <div class="count-shop">
                  <van-stepper
                    v-model="item.count"
                    theme="round"
                    button-size="22"
                    disable-input
                    @change="updateShopbagCount(item.sid, item.count)"
                  />
                </div>
              </div>
            </div>
            <template #right>
              <van-button
                class="shopbag-remove-btn"
                color="#21b276"
                square
                text="删除"
                :key="index"
                @click="removeShopbag([item.sid], index)"
              />
            </template>
          </van-swipe-cell>
        </van-list>
      </div>
    </div>
     <div v-else>
      <div class="empty-box">
        <van-empty description="购物车还没有商品哦!">
          <van-button round color=" #21b276" class="bottom-button" @click="gohome"
            >逛一逛</van-button
          >
        </van-empty>
      </div>
    </div>
    <van-submit-bar
      :price="total"
      button-color="#21b276"
      button-text="提交订单"
      @submit="onSubmit"
    >
      <van-checkbox v-model="checked" @click="allSelect">全选</van-checkbox>
    </van-submit-bar>
   
  </div>
</template>

<script>
import "../assets/less/shopbag.less";
import { mapState, mapMutations } from "vuex";
export default {
  data() {
    return {
      checked: false,
      edit: false,
      shopbagAllData: [],
      shopbagData: [],
      star: 0,
      count: 5,
      finished: false,
      loading: true,
      total: 0,
    };
  },
  created() {
    this.getShopbagData();
  },
  computed: {
    ...mapState(["shopbagCount"]),
  },
  methods: {
    ...mapMutations(["shopbagChange"]),
    back() {
      this.$router.go(-1);
    },
    toggleEdit() {
      this.edit = !this.edit;
    },
    gohome(){
      this.$router.push({name:"Menu"})
    },
    getShopbagData() {
      let tokenString = this.$cookies.get("tokenString");

      if (!tokenString) {
        return this.$router.push({ name: "Login" });
      }
      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        duration: 0,
      });
      this.axios({
        method: "GET",
        url: this.baseUrl + "/findAllShopcart",
        params: {
          appkey: this.appkey,
          tokenString,
        },
      })
        .then((res) => {
          this.$toast.clear();
          // console.log(res);
          if (res.data.code == 700) {
            this.$toast({
              message: res.data.msg,
              forbidClick: true,
              duration: 3000,
            });
            return this.$router.push({ name: "Login" });
          }

          if (res.data.code === 5000) {
            res.data.result.forEach((val) => {
              val.isChecked = false;
            });
            this.shopbagAllData = res.data.result;
            this.shopbagData = this.shopbagAllData.slice(
              this.star,
              this.star + this.count
            );
            // console.log("shopbagData", this.shopbagData);
            this.star += this.count;
            if (this.shopbagAllData.lengtn < this.count) {
              this.finished = true;
              return;
            }
            this.loading = false;
          } else {
            this.$toast({
              message: res.data.msg,
              forbidClick: true,
              duration: 3000,
            });
          }
        })
        .catch((err) => {
          this.$toast.clear();
          console.log("err ==> ", err);
        });
    },
    loadingData() {
      let data = this.shopbagAllData.slice(this.star, this.star + this.count);
      this.shopbagData.push(...data);
      this.star += this.count;

      if (data.length < this.count) {
        this.finished = true;
        return;
      }
      this.loding = false;
    },
    updateShopbagCount(sid, count) {
      let tokenString = this.$cookies.get("tokenString");
      // console.log("tokenString ==> ", tokenString);

      if (!tokenString) {
        console.log("浏览器token不存在");
        return this.$router.push({ name: "Login" });
      }

      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        duration: 0,
      });

      this.axios({
        method: "POST",
        url: this.baseUrl + "/modifyShopcartCount",
        data: {
          appkey: this.appkey,
          tokenString,
          sid,
          count,
        },
      })
        .then((res) => {
          // console.log("res updateShopbagCount ==> ", res);
          this.$toast.clear();

          if (res.data.code == 700) {
            this.$toast({
              message: res.data.msg,
              forbidClick: true,
              duration: 3000,
            });
            return this.$router.push({ name: "Login" });
          }

          if (res.data.code === 6000) {
            this.sum();
          } else {
            this.$toast({
              message: res.data.msg,
              forbidClick: true,
              duration: 3000,
            });
          }
        })
        .catch((err) => {
          this.$toast.clear();
          console.log("err ==> ", err);
        });
    },
    removeShopbag(sids, index) {
      let tokenString = this.$cookies.get("tokenString");

      if (!tokenString) {
        console.log("浏览器token不存在");
        return this.$router.push({ name: "Login" });
      }
      this.axios({
        method: "POST",
        url: this.baseUrl + "/deleteShopcart",
        data: {
          appkey: this.appkey,
          tokenString,
          sids: JSON.stringify(sids),
        },
      })
        .then((res) => {
          this.$toast.clear();
          if (res.data.code == 700) {
            this.$toast({
              message: res.data.msg,
              forbidClick: true,
              duration: 3000,
            });
            return this.$router.push({ name: "Login" });
          }
          if (res.data.code == 7000) {
            if (index !== undefined) {
              this.shopbagData.splice(index, 1);

              this.shopbagChange(this.shopbagCount - 1);

              this.select();
            } else {
              for (let i = 0; i < this.shopbagData.length; i++) {
                if (this.shopbagData[i].isChecked) {
                  this.shopbagData.splice(i, 1);
                  i--;
                }
              }

              this.shopbagChange(this.shopbagCount - sids.length);
              this.sum();
            }

            this.$nextTick(() => {
              let cells = document.querySelectorAll(".shopbag-cell");

              // console.log("cells ==> ", cells);
            });
          }
          this.$toast({
            message: res.data.msg,
            forbidClick: true,
            duration: 3000,
          });
        })
        .catch((err) => {
          this.$toast.clear();
          console.log("err ==> ", err);
        });
    },
    onSubmit() {
      let sids = [];
      this.shopbagData.forEach((v) => {
        if (v.isChecked) {
          sids.push(v.sid);
        }
      });

      if (sids.length === 0) {
        this.$toast({
          message: "选择下单的商品",
          forbidClick: true,
          duration: 3000,
        });

        return;
      }

      this.$router.push({ name: "Pay", query: { sids: sids.join("-") } });
    },
    select() {
      this.sum();
      for (let i = 0; i < this.shopbagData.length; i++) {
        if (!this.shopbagData[i].isChecked) {
          this.checked = false;
          return;
        }
      }
      this.checked = true;
    },
    allSelect() {
      this.shopbagData.forEach((v) => {
        v.isChecked = this.checked;
      });
      this.sum();
    },
    sum() {
      let total = 0;
      this.shopbagData.forEach((val) => {
        if (val.isChecked) {
          total += val.price * val.count;
        }
      });
      this.total = total * 100;
    },
  },
};
</script>